package vip.idiy.anwei_android_iot;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mmkv.MMKV;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import vip.idiy.anwei_android_iot.adapters.MyViewPageAdapter;
import vip.idiy.anwei_android_iot.adapters.RecyclerItemClickListener;
import vip.idiy.anwei_android_iot.adapters.RecyclerViewDeviceAdapter;
import vip.idiy.anwei_android_iot.adapters.ViewType;
import vip.idiy.anwei_android_iot.dialog.IconSelectDialog;
import vip.idiy.anwei_android_iot.dialog.SpaceItemDecoration;
import vip.idiy.anwei_android_iot.domin.DeviceInfo;
import vip.idiy.anwei_android_iot.domin.DeviceScene;
import vip.idiy.anwei_android_iot.domin.DeviceType;
import vip.idiy.anwei_android_iot.domin.IconEntity;
import vip.idiy.anwei_android_iot.utils.MyMqttCallback;
import vip.idiy.anwei_android_iot.domin.mqtt.SubData;
import vip.idiy.anwei_android_iot.utils.ActivityFactory;
import vip.idiy.anwei_android_iot.utils.DatabaseUtil;
import vip.idiy.anwei_android_iot.utils.IotUtil;
import vip.idiy.anwei_android_iot.utils.MQTTUtil;
import vip.idiy.anwei_android_iot.utils.SpUtils;
import vip.idiy.anwei_android_iot.utils.ViewUtil;
import vip.idiy.anwei_android_iot.utils.dbHandle.DeviceInfoHandle;
import vip.idiy.anwei_android_iot.utils.dbHandle.SceneDataHandle;
import vip.idiy.anwei_android_iot.utils.dbHandle.TypeDataHandle;
import vip.idiy.anwei_android_iot.views.LayoutBasicInfo;
import vip.idiy.anwei_android_iot.views.MsgHandler;
import vip.idiy.anwei_android_iot.views.MyViewPager;

// 设备,设置
public class MainActivity extends AppCompatActivity {
    private final String TAG = "myTag " + " MainActivity ";

    // main_radio_group的默认高度, 默认高度 + 获取导航栏高度 = 高度;
    // 168  =  56(dp) * 3(密度)
    private final int main_radio_group_default_height = 168;


    // 主要操作
    private RadioGroup main_radio_group;
    private LayoutInflater inflater;
    private MyViewPager main_my_view_pager;
    private RadioButton main_home_radio_button;
    private DeviceInfoHandle deviceInfoHandle;
    private final int DEFAULT_PAGE = 1;
    private TextView layout_home_table_total_text_view;
    private EditText layout_home_table_page_edit_text;
    private int now_page;
    private RecyclerView layout_home_recycler_view;
    private List<DeviceInfo> deviceInfoList;
    private ArrayList<ViewType> viewTypes;
    private DatabaseUtil databaseUtil;
    private SceneDataHandle sceneDataHandle;
    private TypeDataHandle typeDataHandle;
    private EditText layout_home_table_query_type_content_edit_text;
    ArrayList<String> columnNames = new ArrayList<>();
    ArrayList<String> columnValues = new ArrayList<>();
    private EditText layout_home_table_query_scene_content_edit_text;
    private RecyclerViewDeviceAdapter recyclerViewDeviceAdapter;

    // 线程池
    private ScheduledExecutorService scheduler;

    private MQTTUtil mqttUtil;
    private BroadcastReceiver receiver;


    private final int MQTT_RECONNECT_MQTT = 2001;
    private MsgHandler msgHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置设透明状态栏,导航栏. 状态栏字体修改为黑色
        ViewUtil.setViewStyle(this, true);

        ActivityFactory.setMainActivity(this);

        initMMKV();

        // 获取DatabaseUtil实例
        databaseUtil = DatabaseUtil.getInstance(this);
        deviceInfoHandle = new DeviceInfoHandle(databaseUtil);
        sceneDataHandle = new SceneDataHandle(databaseUtil);
        typeDataHandle = new TypeDataHandle(databaseUtil);
        // 插入测试数据
        // insertTestData();

        // 初始化窗口
        initView();

        // 获取MQTT信息
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 在这里处理消息
                String topic = intent.getStringExtra("topic");
                String message = intent.getStringExtra("message");
                String[] topicSplit = topic.split("/");
                switch (topicSplit.length) {
                    case 2:
                        mqttDataHandle(message);
                        break;
                    case 6:
                        if (topicSplit[5].equals("connected")) { // 设备上线
                            mqttDeviceLinkStatus(true, topicSplit[4]);
                        } else if (topicSplit[5].equals("disconnected")) { // 设备离线
                            mqttDeviceLinkStatus(false, topicSplit[4]);
                        }
                    default:
                        break;
                }
            }
        };
        IntentFilter filter = new IntentFilter("MQTT_MESSAGE_ARRIVED");
        registerReceiver(receiver, filter);

        /**
         * 消息处理
         */
        msgHandler = new MsgHandler(msg -> {
            switch (msg.what) {
                case MQTT_RECONNECT_MQTT:
                    connectMQTT();
                    break;

                default:
                    break;
            }
        });
        // 连接MQTT(自动重连)
        startReconnect();
    }

    private void initMMKV() {
        String dir = getPath(this) + File.separator + "android_iot/mmkv";
        MMKV.initialize(this, dir);
        SpUtils.getInstance();

        MQTTUtil.setMqttUser(SpUtils.decodeString("mqtt_name"));
        MQTTUtil.setMqttPassword(SpUtils.decodeString("mqtt_password"));
        MQTTUtil.setMqttServer(SpUtils.decodeString("mqtt_server"));
    }

    /**
     * 连接MQTT
     */
    private void connectMQTT() {
        mqttUtil = MQTTUtil.getInstance();
        if (mqttUtil.isConnect())
            return;
        mqttUtil.connectMQTT(new MyMqttCallback(this) {
        }, new MQTTUtil.OnConnectListener() {
            @Override
            public void onSuccess() { // 连接成功;
                Log.i(TAG, "onSuccess: 连接成功");
                mqttUtil.subscribeMQTT();
            }

            @Override
            public void onFailure() {  // 连接失败
                // Handle failure
                Log.i(TAG, "onFailure: 连接失败");
            }
        });
    }

    /**
     * 判断连接mqtt 循环任务
     */
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(() -> {
            Message message = new Message();
            message.what = MQTT_RECONNECT_MQTT;
            msgHandler.sendMessage(message);
        }, 0, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    /**
     * 处理设备上下状态
     *
     * @param b
     * @param data
     */
    private void mqttDeviceLinkStatus(boolean b, String data) {
        DeviceInfo di = deviceInfoHandle.selectByDeviceId(data);
        di.setOnLine(b);
        di.setRssi(b ? 0 : -101);
        deviceInfoHandle.update(di);
        // 更新页面
        for (int i = 0; i < viewTypes.size(); i++) {
            DeviceInfo d = (DeviceInfo) viewTypes.get(i);
            if (d.getDeviceId().equals(data)) {
                d.setOnLine(b);
                d.setRssi(b ? 0 : -101);
                d.setRssiDrawable(IotUtil.checkRssi(d.getRssi()));
                recyclerViewDeviceAdapter.notifyItemChanged(i);
                break;
            }
        }
    }

    /**
     * 处理MQTT接收到的信息
     *
     * @param data
     */
    private void mqttDataHandle(String data) {
        SubData subData = IotUtil.analysisResult(data, SubData.class);
        // 保存数据库
        DeviceInfo di = deviceInfoHandle.selectByDeviceId(subData.getDeviceId());
        di.setFirmwareVersion(subData.getFirmwareVersion());
        di.setOnLine(true);
        di.setRssi(subData.getRssi());
        di.setDeviceData(data);
        deviceInfoHandle.update(di);
        // 更新页面
        for (int i = 0; i < viewTypes.size(); i++) {
            DeviceInfo d = (DeviceInfo) viewTypes.get(i);
            if (d.getDeviceId().equals(subData.getDeviceId())) {
                d.setOnLine(true);
                d.setRssi(subData.getRssi());
                d.setRssiDrawable(IotUtil.checkRssi(d.getRssi()));
                recyclerViewDeviceAdapter.notifyItemChanged(i);
                break;
            }
        }
    }

    /**
     * 加入测试数据
     */
    private void insertTestData() {
        for (int i = 0; i < 50; i++) {
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDeviceId("14450421" + i);
            deviceInfo.setTypeId(1);
            deviceInfo.setSceneId(1);
            deviceInfo.setRssi(-101);
            boolean result = deviceInfoHandle.insert(deviceInfo);
            Log.i(TAG, "insertTestData: " + result);
        }
    }

    /**
     * 初始化窗口
     */
    private void initView() {
        // 主要操作
        main_radio_group = findViewById(R.id.main_radio_group);

        // 主界面viewPager
        main_my_view_pager = findViewById(R.id.main_my_view_pager);
        // 页面List
        ArrayList<View> views = new ArrayList<>();
        inflater = LayoutInflater.from(this);
        // 初始化首页界面
        View layout_home = initHome();
        // 初始化设置界面
        View layout_setting = initSetting();

        // 设置加入主页的viewPager
        views.add(layout_home);
        views.add(layout_setting);
        main_my_view_pager.setAdapter(new MyViewPageAdapter(views));

        main_home_radio_button = findViewById(R.id.main_home_radio_button);
        main_home_radio_button.setOnClickListener(view -> main_my_view_pager.setCurrentItem(0));

        // 设置app打开后默认选择首页
        defaultSelectHome();

        // 设备管理
        findViewById(R.id.main_device_handle_radio_button)
                .setOnClickListener(v -> startActivity(new Intent(MainActivity.this, DeviceHandleActivity.class)));
        // 位置管理
        findViewById(R.id.main_scene_handle_radio_button)
                .setOnClickListener(v -> startActivity(new Intent(MainActivity.this, SceneHandleActivity.class)));

        // 类型管理
        findViewById(R.id.main_type_handle_radio_button)
                .setOnClickListener(v -> startActivity(new Intent(MainActivity.this, TypeHandleActivity.class)));

        // 设置按钮,点击跳转设置页面
        findViewById(R.id.main_setting_radio_button)
                .setOnClickListener(view -> main_my_view_pager.setCurrentItem(1));
    }

    /**
     * 获取列表
     *
     * @param columnNames
     * @param columnValues
     * @param page
     */
    private void getDeviceList(String[] columnNames, String[] columnValues, int page) {
        int count = deviceInfoHandle.getTotalRecordCount(columnNames, columnValues);
        if (count == 0) {
            layout_home_table_total_text_view.setText(String.format(getResources().getString(R.string.data_total), 0));
            Toast.makeText(this, R.string.error_data_is_null, Toast.LENGTH_SHORT).show();
            return;
        }
        // 计算总页数
        int totalPages = IotUtil.getTotalPages(count, 15);
        if (page > totalPages) {
            Toast.makeText(this, R.string.error_page_is_max, Toast.LENGTH_SHORT).show();
            return;
        }
        if (page == 0) {
            Toast.makeText(this, R.string.error_page_is_min, Toast.LENGTH_SHORT).show();
            return;
        }
        // 清空
        layout_home_recycler_view.setAdapter(null);
        // 获取列表
        deviceInfoList.clear();
        // 清空
        viewTypes.clear();
        // 当前页
        now_page = page;

        layout_home_table_page_edit_text.setText(String.valueOf(page));
        layout_home_table_total_text_view.setText(String.format(getResources().getString(R.string.data_total), totalPages));

        deviceInfoList = deviceInfoHandle.getList(columnNames, columnValues, page);

        for (DeviceInfo d : deviceInfoList) {
            d.setRssiDrawable(IotUtil.checkRssi(d.getRssi()));
            d.setTypeImgDrawable(IotUtil.checkImg(d.getSceneIcon()).getIcon());
            viewTypes.add(d);
        }
        recyclerViewDeviceAdapter = new RecyclerViewDeviceAdapter(MainActivity.this, viewTypes);
        // 设置显示每行5个
        StaggeredGridLayoutManager layoutManager =
                new StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL);
        layout_home_recycler_view.setLayoutManager(layoutManager);
        layout_home_recycler_view.setAdapter(recyclerViewDeviceAdapter);
    }

    /**
     * 初始化设置页面
     *
     * @return
     */
    @SuppressLint("InflateParams")
    private View initSetting() {
        View layout_setting = inflater.inflate(R.layout.layout_setting, null);
        // 标题
        TextView layout_reuse_head_tv_title = layout_setting.findViewById(R.id.layout_reuse_head_tv_title);
        layout_reuse_head_tv_title.setText(R.string.title_setting);
        layout_setting.findViewById(R.id.layout_reuse_head_return_myImageButton).setOnClickListener(v -> finish());

        LinearLayout layout_setting_linear = layout_setting.findViewById(R.id.layout_setting_linear);

        // MQTT用户名
        LayoutBasicInfo basicInfo_setting_mqtt_name = new LayoutBasicInfo(this).init(false, false, false, true, false, false)
                .setLeftText(getString(R.string.setting_mqtt_name))
                .setLineBackground(R.drawable.ripple_gray);
        basicInfo_setting_mqtt_name.setCentreEditContent(SpUtils.decodeString("mqtt_name"));

        // MQTT密码
        LayoutBasicInfo basicInfo_setting_mqtt_password = new LayoutBasicInfo(this).init(false, false, false, true, false, false)
                .setLeftText(getString(R.string.setting_mqtt_password))
                .setLineBackground(R.drawable.ripple_gray);
        basicInfo_setting_mqtt_password.setCentreEditContent(SpUtils.decodeString("mqtt_password"));

        // MQTT服务器
        LayoutBasicInfo basicInfo_setting_mqtt_server = new LayoutBasicInfo(this).init(false, false, false, true, false, false)
                .setLeftText(getString(R.string.setting_mqtt_server))
                .setLineBackground(R.drawable.ripple_gray);
        basicInfo_setting_mqtt_server.setCentreEditContent(SpUtils.decodeString("mqtt_server"));

        // 检查版本
        LayoutBasicInfo basicInfo_setting_check_version = new LayoutBasicInfo(this).init(false, true, false, false, false, true)
                .setLeftText(getString(R.string.setting_check_version))
                .setCentreContent(BuildConfig.VERSION_NAME)
                .setLineBackground(R.drawable.ripple_gray)
                .setRightImg(R.mipmap.icon_right)
                .setLineClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 获取新版本
                    }
                });

        // 关于
        LayoutBasicInfo basicInfo_setting_about = new LayoutBasicInfo(this).init(false, true, false, false, false, true)
                .setLeftText(getString(R.string.setting_about))
                .setLineBackground(R.drawable.ripple_gray)
                .setRightImg(R.mipmap.icon_right)
                .setLineClick(v -> {
                    Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                    startActivity(intent);
                });

        // 保存
        layout_setting.findViewById(R.id.layout_setting_save).setOnClickListener(v -> {
            SpUtils.encode("mqtt_name", basicInfo_setting_mqtt_name.getCentreEditContent());
            SpUtils.encode("mqtt_password", basicInfo_setting_mqtt_password.getCentreEditContent());
            SpUtils.encode("mqtt_server", basicInfo_setting_mqtt_server.getCentreEditContent());
            Toast.makeText(this, R.string.save_success, Toast.LENGTH_SHORT).show();
        });

        layout_setting_linear.addView(basicInfo_setting_mqtt_name);
        layout_setting_linear.addView(basicInfo_setting_mqtt_password);
        layout_setting_linear.addView(basicInfo_setting_mqtt_server);
        layout_setting_linear.addView(basicInfo_setting_check_version);
        layout_setting_linear.addView(basicInfo_setting_about);
        return layout_setting;
    }

    /**
     * 初始化首页
     *
     * @return
     */
    @SuppressLint("InflateParams")
    private View initHome() {
        View layout_home = inflater.inflate(R.layout.layout_home, null);
        // 一键配网
        layout_home.findViewById(R.id.layout_home_smartConfigWait).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SmartConfigWaitActivity.class);
                startActivity(intent);
            }
        });
        // 共N页
        layout_home_table_total_text_view = layout_home.findViewById(R.id.layout_home_table_total_text_view);
        // 当前页
        layout_home_table_page_edit_text = layout_home.findViewById(R.id.layout_home_table_page_edit_text);
        // 上一页
        layout_home.findViewById(R.id.layout_home_table_prev_page).setOnClickListener(v -> {
            String page = layout_home_table_page_edit_text.getText().toString().trim();
            getDeviceList(null, null, StringUtils.isEmpty(page) ? DEFAULT_PAGE : Integer.parseInt(page) - 1);
        });
        // 下一页
        layout_home.findViewById(R.id.layout_home_table_next_page).setOnClickListener(v -> {
            String page = layout_home_table_page_edit_text.getText().toString().trim();
            getDeviceList(null, null, StringUtils.isEmpty(page) ? DEFAULT_PAGE : Integer.parseInt(page) + 1);
        });
        // 刷新
        layout_home.findViewById(R.id.layout_home_table_flush_myImageButton).setOnClickListener(v -> getDeviceList(null, null, now_page));
        // 查询
        layout_home.findViewById(R.id.layout_home_table_query_myImageButton).setOnClickListener(
                v -> getDeviceList(columnNames.toArray(new String[columnNames.size()]), columnValues.toArray(new String[columnValues.size()]), DEFAULT_PAGE));
        // 清空查询
        layout_home.findViewById(R.id.layout_home_table_clear_myImageButton).setOnClickListener(v -> {
            columnValues.clear();
            columnNames.clear();
            layout_home_table_query_type_content_edit_text.setText("");
            layout_home_table_query_scene_content_edit_text.setText("");
            getDeviceList(null, null, DEFAULT_PAGE);
        });
        // 查询类型
        layout_home_table_query_type_content_edit_text = layout_home.findViewById(R.id.layout_home_table_query_type_content_edit_text);
        layout_home_table_query_type_content_edit_text.setInputType(InputType.TYPE_NULL);
        // 弹出选择框
        layout_home_table_query_type_content_edit_text.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                // 读入类型数据,转成枚举类
                List<DeviceType> list = typeDataHandle.getList(null, null);
                ArrayList<IconEntity> iconLit = new ArrayList<>();
                for (DeviceType t : list) {
                    IconEntity iconEntity = new IconEntity(t.getTypeName(), IotUtil.checkImg(t.getTypeImg()).getIcon(), t.getTypeId());
                    iconLit.add(iconEntity);
                }
                IconSelectDialog dialog = IconSelectDialog.newInstance(
                        MainActivity.this,
                        getString(R.string.please_select_query_type),
                        entity -> {
                            layout_home_table_query_type_content_edit_text.setText(entity.getIconName());
                            // 添加查询参数
                            columnNames.add("device_info.type_id");
                            columnValues.add(String.valueOf(entity.getQueryId()));
                            // 取消焦点
                            layout_home_table_query_type_content_edit_text.clearFocus();
                        }, iconLit);
                dialog.show();
            }
        });
        // 查询位置
        layout_home_table_query_scene_content_edit_text = layout_home.findViewById(R.id.layout_home_table_query_scene_content_edit_text);
        layout_home_table_query_scene_content_edit_text.setInputType(InputType.TYPE_NULL);
        layout_home_table_query_scene_content_edit_text.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                List<DeviceScene> list = sceneDataHandle.getList(null, null);
                ArrayList<IconEntity> iconLit = new ArrayList<>();
                for (DeviceScene s : list) {
                    IconEntity iconEntity = new IconEntity(s.getSceneName(), IotUtil.checkIcon(s.getSceneIcon()).getIcon(), s.getSceneId());
                    iconLit.add(iconEntity);
                }
                IconSelectDialog dialog = IconSelectDialog.newInstance(
                        MainActivity.this,
                        getString(R.string.please_select_query_type),
                        entity -> {
                            layout_home_table_query_scene_content_edit_text.setText(entity.getIconName());
                            // 添加查询参数
                            columnNames.add("device_info.scene_id");
                            columnValues.add(String.valueOf(entity.getQueryId()));
                            // 取消焦点
                            layout_home_table_query_scene_content_edit_text.clearFocus();
                        },
                        iconLit);
                dialog.show();
            }
        });

        layout_home_recycler_view = layout_home.findViewById(R.id.layout_home_recycler_view);
        ((SimpleItemAnimator) Objects.requireNonNull(layout_home_recycler_view.getItemAnimator())).setSupportsChangeAnimations(false);
        layout_home_recycler_view.addItemDecoration(new SpaceItemDecoration(10));

        viewTypes = new ArrayList<>();
        deviceInfoList = new ArrayList<>();
        getDeviceList(null, null, DEFAULT_PAGE);
        layout_home_recycler_view.addOnItemTouchListener(new RecyclerItemClickListener(this, layout_home_recycler_view, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(MainActivity.this, DeviceSettingHandleActivity.class);
                DeviceInfo d = (DeviceInfo) viewTypes.get(position);
                intent.putExtra("deviceId", d.getDeviceId());
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        }));
        return layout_home;
    }

    /**
     * 获取路径
     *
     * @param context
     * @return
     */
    public String getPath(Context context) {
        File dir;
        boolean state = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (state) {
            if (Build.VERSION.SDK_INT >= 29) {
                //Android10之后
                dir = context.getExternalFilesDir(null);
            } else {
                dir = Environment.getExternalStorageDirectory();
            }
        } else {
            dir = Environment.getRootDirectory();
        }
        return dir.toString();
    }

    /**
     * 设置默认选择首页
     */
    public void defaultSelectHome() {
        main_my_view_pager.setCurrentItem(0);
        main_home_radio_button.setChecked(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scheduler != null) {
            scheduler.shutdown();
        }
        mqttUtil.disconnect();
        unregisterReceiver(receiver);
    }
}